package com.rjwh.dingdong.client.activity.radio;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.player.fragment.PlayerToolbarFragment;
import com.rjwh.dingdong.client.adapter.RadioAlbumListAdapter;
import com.rjwh.dingdong.client.bean.localbean.RadioAnchorInfo;
import com.rjwh.dingdong.client.bean.localbean.RadioPageAlbumData;
import com.rjwh.dingdong.client.mvp.presenter.impl.RadioAnchorHomePagePresenter;
import com.rjwh.dingdong.client.mvp.view.RadioAnchorHomePageView;
import com.rjwh.dingdong.client.util.StatusBarUtils;
import com.rjwh.dingdong.client.util.UrlUtil;
import com.rjwh.dingdong.client.view.PullToZoomListView;
import com.rjwh.dingdong.client.widget.RoundImageView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * @author Kay
 * @ClassName RadioAlbumProgramActivity
 * @Description 主播主页(主播专辑列表)
 * @date 2016-10-26
 * @history 2016-10-26 author: description:
 */
public class RadioAnchorHomePageActivity extends BaseActivity implements RadioAnchorHomePageView, AbsListView.OnScrollListener {

    @BindView(R.id.transparency_toolbar)
    Toolbar toolbar;
    @BindView(R.id.transparency_app_bar_layout)
    AppBarLayout transparencyAppBarLayout;
    @BindView(R.id.loading_layout)
    RelativeLayout loadingLayout;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    @BindView(R.id.radio_album_home_page_list)
    PullToZoomListView radioAlbumHomePageList;

    private RadioAlbumListAdapter adapter;
    private String anchorid;

    private RadioAnchorHomePagePresenter presenter;
    private RoundImageView radioAlbumProgramAvatarImg;
    private TextView radioAlbumProgramNameTv;
    private TextView radioAlbumProgramPlayTimesTv;
    private TextView radioAlbumProgramFansTv;
    private ImageView radioAlbumProgramBannerFollowBtn;
    //测量值
    private float headerHeight;//顶部banner高度
    private float minHeaderHeight;//顶部最低高度，即Bar的高度
    private String radioname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.radio_album_home_page_layout);
        ButterKnife.bind(this);
        parseIntent();
        initMeasure();
        initView();

        presenter = new RadioAnchorHomePagePresenter(this, this);
        doGetRadioAlbumProgram();
    }

    private void doGetRadioAlbumProgram() {
        hideErrorView();
        showLoadingView();
        presenter.doGetAnchorHomePage(anchorid);
    }

    public static void startActivity(Context context, String anchorid, String albumid) {
        Intent intent = new Intent(context, RadioAnchorHomePageActivity.class);
        intent.putExtra("anchorid", anchorid);
        context.startActivity(intent);
    }

    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            anchorid = intent.getStringExtra("anchorid");
        }
    }

    private void initMeasure() {
        headerHeight = getResources().getDimension(R.dimen.radio_program_banner_height);
        minHeaderHeight = getResources().getDimension(R.dimen.abc_action_bar_default_height_material);
    }

    private void initView() {
        initToolbarHelper();

        getSupportFragmentManager().beginTransaction().replace(R.id.radio_album_home_page_fm, PlayerToolbarFragment.getInstance()).commit();

        View headerView = View.inflate(getApplicationContext(), R.layout.radio_album_program_header, null);
        radioAlbumProgramAvatarImg = (RoundImageView) headerView.findViewById(R.id.radio_album_program_avatar_img);
        radioAlbumProgramNameTv = (TextView) headerView.findViewById(R.id.radio_album_program_name_tv);
        radioAlbumProgramPlayTimesTv = (TextView) headerView.findViewById(R.id.radio_album_program_play_times_tv);
        radioAlbumProgramFansTv = (TextView) headerView.findViewById(R.id.radio_album_program_fans_tv);
        radioAlbumProgramBannerFollowBtn = (ImageView) headerView.findViewById(R.id.radio_album_program_banner_follow_btn);

        //设置header大小
        radioAlbumHomePageList.setHeaderViewSize(ViewGroup.LayoutParams.MATCH_PARENT, (int) headerHeight);
        //设置headerView
        radioAlbumHomePageList.getHeaderContainer().addView(headerView);
        radioAlbumHomePageList.setHeaderView();
        adapter = new RadioAlbumListAdapter(this, false);
        radioAlbumHomePageList.setAdapter(adapter);
        radioAlbumHomePageList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position < 1) {
                    return;
                }
                RadioPageAlbumData item = adapter.getItem(position - 1);
                String actionurl = item.getActionurl();
                if (!AsStrUtils.isEmpty(actionurl)) {
                    UrlUtil.handelUrl(RadioAnchorHomePageActivity.this, actionurl, true);
                }
            }
        });
        radioAlbumHomePageList.setOnScrollListener(this);
    }

    private void updateView(RadioAnchorInfo basicinfo) {
        String radiocover = basicinfo.getRadiocover();
        String radioavatar = basicinfo.getRadioavatar();
        String radioname = basicinfo.getRadioname();
        String playcount = basicinfo.getPlaycount();
        String fans = basicinfo.getFans();
        int follow = basicinfo.getFollow();

        Glide.with(this).load(radiocover).dontAnimate().placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_radio_top_bg)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(radioAlbumHomePageList.getHeaderView());

        Glide.with(this).load(radioavatar).dontAnimate().placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_pic_holder)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(radioAlbumProgramAvatarImg);
        if (!AsStrUtils.isEmpty(radioname)) {
            this.radioname = radioname;
            radioAlbumProgramNameTv.setText(radioname);
        }
        if (!AsStrUtils.isEmpty(playcount)) {
            radioAlbumProgramPlayTimesTv.setText(String.format(getResources().getString(R.string.radio_album_play_times_format), playcount));
        }
        if (!AsStrUtils.isEmpty(fans)) {
            radioAlbumProgramFansTv.setText(String.format(getResources().getString(R.string.radio_album_fans_format), fans));
        }

        if (follow == 1) {
            radioAlbumProgramBannerFollowBtn.setImageResource(R.drawable.icon_radio_album_followed);
        } else {
            radioAlbumProgramBannerFollowBtn.setImageResource(R.drawable.icon_radio_album_unfollow);
        }

    }

    protected void initToolbarHelper() {
        this.setSupportActionBar(this.toolbar);
        assert getSupportActionBar() != null;
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public void showLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void showErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadData(RadioAnchorInfo basicinfo, List<RadioPageAlbumData> albumlist) {
        updateView(basicinfo);
        adapter.clearAll();
        adapter.appendToList(albumlist);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
//        if (scrollState == SCROLL_STATE_IDLE) {
//        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        //Y轴偏移量
        float scrollY = getScrollY(view);

        //变化率
        float headerBarOffsetY = headerHeight - minHeaderHeight;//Toolbar与header高度的差值
        float offset = 1 - Math.max((headerBarOffsetY - scrollY) / headerBarOffsetY, 0f);

        //Toolbar背景色透明度
        transparencyAppBarLayout.setBackgroundColor(Color.argb((int) (offset * 255), 255, 255, 255));

        /*** 标题文字处理 ***/
        //判断标题文字的显示
        if (scrollY > headerBarOffsetY) {
            if (radioname != null) {
                toolbar.setTitle(radioname);
            }
        } else {
            toolbar.setTitle("");
        }
    }

    /**
     * 得到ListView在Y轴上的偏移
     */
    public float getScrollY(AbsListView view) {
        View c = view.getChildAt(0);

        if (c == null)
            return 0;

        int firstVisiblePosition = view.getFirstVisiblePosition();
        int top = c.getTop();

        float headerHeight = 0;
        if (firstVisiblePosition >= 1) {
            headerHeight = this.headerHeight;
            StatusBarUtils.from(this)
                    .setTransparentStatusbar(true)//状态栏是否透明
                    .setTransparentNavigationbar(false)//Navigationbar是否透明
                    .setLightStatusBar(true)//状态栏字体是否为亮色
                    .process();
        } else {
            StatusBarUtils.from(this)
                    .setTransparentStatusbar(true)//状态栏是否透明
                    .setTransparentNavigationbar(false)//Navigationbar是否透明
                    .setLightStatusBar(false)//状态栏字体是否为亮色
                    .process();
        }
        return -top + firstVisiblePosition * c.getHeight() + headerHeight;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
    }
}
